package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//提现记录
func ListWithdraw(p ListParams, t ListDayParams, groupId, id, uid, status int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, int64, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := "1=1"

	if groupId != 0 {
		where = fmt.Sprintf("u.group_id = %v", groupId)
	}

	if id != 0 {
		where = where + fmt.Sprintf(" AND w.id = %v", id)
	}
	if uid != 0 {
		where = where + fmt.Sprintf(" AND w.agent_id = %v", uid)
	}
	if status != 0 {
		where = where + fmt.Sprintf(" AND w.status = %v", status)
	}
	where2 := " 1=1 "
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND w.create_time >= %v AND w.create_time < %v", t.StartTime, t.EndTime)
		where2 = fmt.Sprintf(" AND w.create_time >= %v AND w.create_time < %v", t.StartTime, t.EndTime)
	}

	sql := fmt.Sprintf(`
		SELECT
			w.*,b.name,b.bank_name,b.province,b.city,b.card_num,b.branch
		FROM
			%v AS w
		INNER JOIN
			%v AS u
		ON w.agent_id = u.uid
		LEFT JOIN
			%v AS b
		ON w.agent_id = b.uid
		WHERE
			%v
		ORDER BY
			w.id DESC
		LIMIT ?,?
	`, TableH5WithdrawRecord, TableH5User, TableH5AgentBank, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&wr)
	if CheckError(err) {
		return wr, 0, 0, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS w INNER JOIN %v AS u ON w.agent_id = u.uid WHERE %v`,
		TableH5WithdrawRecord, TableH5User, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return wr, 0, 0, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(w.amount) is NULL,0,SUM(w.amount)) AS processed_amount
		FROM
			%v AS w
		WHERE
			%v AND w.status = %v
	`, TableH5WithdrawRecord, where2, WithdrawPaySuccess)
	var pAmount, uAmount int64
	o.Raw(sql).QueryRow(&pAmount)
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(w.amount) is NULL,0,SUM(w.amount)) AS unprocessed_amount
		FROM
			%v AS w
		WHERE
			%v AND w.status < %v
	`, TableH5WithdrawRecord, where2, WithdrawPaySuccess)
	o.Raw(sql).QueryRow(&uAmount)
	return wr, count, pAmount, uAmount, nil
}

//更新提现记录(一般就是状态及失败原因)
func UpdateWithdraw(wr map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessCenter)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableH5WithdrawRecord, wr, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//获取提现信息
func WithdrawById(id int64, multiOrm ...orm.Ormer) (*WithdrawRecord, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TableH5WithdrawRecord, id)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr WithdrawRecord
	err := o.Raw(sql).QueryRow(&wr)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &wr, err
}

//新增提成规则
func NewRule(cp map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	values, sql := InsertSql(TableH5Rule, cp)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//更新提成规则
func UpdateRule(cr map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf(`type = %v`, id)
	values, sql := UpdateSql(TableH5Rule, cr, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//删除提成规则
func DeleteRule(typ int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf("type=%v", typ)
	sql := DeleteSql(TableH5Rule, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//列出提成规则
func ListRule(multiOrm ...orm.Ormer) ([]*Rule, error) {
	sql := fmt.Sprintf(`
		SELECT
			type AS id, type,name,amount,scale,unit
		FROM
			%v
	`, TableH5Rule)
	o := NewOrm(multiOrm, DBChessSysData)
	var bl []*Rule
	_, err := o.Raw(sql).QueryRows(&bl)
	if CheckError(err) {
		return nil, err
	}
	return bl, nil
}

//更新支付方式比例
func UpdatePayType(cr map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TablePayType, cr, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//列出支付方式比例
func ListPayType(multiOrm ...orm.Ormer) ([]PayType, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
	`, TablePayType)
	o := NewOrm(multiOrm, DBChessSysData)
	var bl []PayType
	_, err := o.Raw(sql).QueryRows(&bl)
	if CheckError(err) {
		return nil, err
	}
	return bl, nil
}

type H5SysUser struct {
	Nickname string `json:"nickname"`
	Phone    string `json:"phone"`
	AuthCode string `json:"auth_code"`
}

//列出H5系统帐号的信息(手机号，名字，授权码)
func ListH5SystemUser(multiOrm ...orm.Ormer) (H5SysUser, error) {
	sql := fmt.Sprintf(`
		SELECT
			nickname,phone,auth_code
		FROM
			%v AS u
		INNER JOIN
			%v AS a
		ON u.uid = a.uid
		WHERE
			u.uid = 0
	`, TableH5User, TableH5AuthCode)
	o := NewOrm(multiOrm, DBChessCenter)
	var user H5SysUser
	err := o.Raw(sql).QueryRow(&user)
	if CheckError(err) {
		return user, err
	}
	return user, nil
}

//更新代理第一次充值的金额及钻石数量
func UpdateTopUp(tu map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableH5TopUp, tu, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func ListTopUp(multiOrm ...orm.Ormer) ([]*TopUp, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
	`, TableH5TopUp)
	o := NewOrm(multiOrm, DBChessSysData)
	var tu []*TopUp
	_, err := o.Raw(sql).QueryRows(&tu)
	if CheckError(err) {
		return nil, err
	}
	return tu, nil
}

//列出钻石房价列表
func ListCardPrice(p ListParams, multiOrm ...orm.Ormer) ([]*Card, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT * FROM %v ORDER BY type,num LIMIT ?,?
		`, TableH5CardPrice)
	o := NewOrm(multiOrm, DBChessSysData)
	var card []*Card
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&card)
	if CheckError(err) {
		return nil, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v`, TableH5CardPrice)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return card, count, nil
}

//新增钻石房价
func NewCardPrice(cp map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	values, sql := InsertSql(TableH5CardPrice, cp)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//删除钻石
func DeleteCardPrice(id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf("id=%v", id)
	sql := DeleteSql(TableH5CardPrice, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//更新钻石
func UpdateCardPrice(tu map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableH5CardPrice, tu, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//获取钻石信息
func CardPriceById(id interface{}, multiOrm ...orm.Ormer) (*Card, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TableH5CardPrice, id)
	o := NewOrm(multiOrm, DBChessSysData)
	var card Card
	err := o.Raw(sql).QueryRow(&card)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &card, err
}

//-----------------以下是商城商品相关-----------------------------
//列出商城商品列表
func ListStorePrice(p ListParams, multiOrm ...orm.Ormer) ([]*Store, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT * FROM %v ORDER BY num LIMIT ?,?
		`, TableStore)
	o := NewOrm(multiOrm, DBChessSysData)
	var store []*Store
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&store)
	if CheckError(err) {
		return nil, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v`, TableStore)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}

	return store, count, nil
}

//新增商城商品
func NewStorePrice(cp map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	values, sql := InsertSql(TableStore, cp)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//删除商城商品
func DeleteStorePrice(id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf("id=%v", id)
	sql := DeleteSql(TableStore, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//更新商城商品
func UpdateStorePrice(tu map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableStore, tu, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//获取商城商品信息
func StorePriceById(id interface{}, multiOrm ...orm.Ormer) (*Store, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TableStore, id)
	o := NewOrm(multiOrm, DBChessSysData)
	var store Store
	err := o.Raw(sql).QueryRow(&store)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &store, err
}

//----------------------------以上是商城商品相关---------------------

//-----------------以下是金币兑换相关-----------------------------
//列出商城商品列表
func ListCoin(p ListParams, multiOrm ...orm.Ormer) ([]*DiamondCoin, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT * FROM %v ORDER BY diamond LIMIT ?,?
		`, TableDiamondCoin)
	o := NewOrm(multiOrm, DBChessSysData)
	var store []*DiamondCoin
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&store)
	if CheckError(err) {
		return nil, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v`, TableDiamondCoin)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}

	return store, count, nil
}

//新增商城商品
func NewCoin(data map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	values, sql := InsertSql(TableDiamondCoin, data)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//删除商城商品
func DeleteCoin(id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf("id=%v", id)
	sql := DeleteSql(TableDiamondCoin, condition)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//更新钻石兑换金币
func UpdateCoin(data map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessSysData)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableDiamondCoin, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//获取钻石兑换金币信息
func CoinById(id interface{}, multiOrm ...orm.Ormer) (*DiamondCoin, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TableDiamondCoin, id)
	o := NewOrm(multiOrm, DBChessSysData)
	var coin DiamondCoin
	err := o.Raw(sql).QueryRow(&coin)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &coin, err
}

//----------------------------以上是金币兑换相关---------------------

//玩家的订单列表(玩家在代理的店铺支付的记录)
func ListPlayerOrder(p ListParams, t ListDayParams, order AllOrderParams, multiOrm ...orm.Ormer) ([]*Order, int64, int64, error) {
	where := "user_type = 2"
	if order.Uid != 0 {
		where = where + fmt.Sprintf(" AND uid = %v", order.Uid)
	}
	if order.TransactionId != "" {
		where = where + fmt.Sprintf(" AND transaction_id = %v", order.TransactionId)
	}
	if order.Id != 0 {
		where = where + fmt.Sprintf(" AND id = %v", order.Id)
	}
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND order_time >= %v AND order_time < %v", t.StartTime, t.EndTime)
	}
	//计算订单总金额时，默认只计算支付成功未发货和已发货这两种状态
	where2 := where
	if order.Status != 0 {
		where = where + fmt.Sprintf(" AND status = %v", order.Status)
		where2 = where
	} else {
		where2 = where2 + fmt.Sprintf(" AND status IN(%v,%v)", OrderPaySuccess, OrderDelivered)
	}

	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY
			id DESC
		LIMIT ?,?
	`, TableH5Order, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr []*Order
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&wr)
	if CheckError(err) {
		return nil, 0, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`,
		TableH5Order, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, 0, err
	}

	//计算支付金额
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(amount) is NULL,0,SUM(amount))
		FROM
			%v
		WHERE
			%v
	`, TableH5Order, where2)
	var amount int64
	o.Raw(sql).QueryRow(&amount)

	return wr, amount, count, nil
}

//代理的订单列表
func ListAgentOrder(p ListParams, t ListDayParams, order AllOrderParams, groupId int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, int64, error) {
	where := "o.user_type = 1"
	if groupId != 0 { //groupId不为0表示pc用户不是隶属于公司，所以不能查看所有的订单
		where = where + fmt.Sprintf(" AND u.group_id = %v", groupId)
	} else { //group_id = 0所属区域为公司,可以查看所有的订单
		if order.GroupId != 0 {
			where = where + fmt.Sprintf(" AND u.group_id = %v", order.GroupId)
		}
	}
	if order.Uid != 0 {
		where = where + fmt.Sprintf(" AND o.uid = %v", order.Uid)
	}
	if order.TransactionId != "" {
		where = where + fmt.Sprintf(" AND o.transaction_id = %v", order.TransactionId)
	}
	if order.Id != 0 {
		where = where + fmt.Sprintf(" AND o.id = %v", order.Id)
	}

	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND o.order_time >= %v AND o.order_time < %v", t.StartTime, t.EndTime)
	}
	//计算订单总金额时，默认只计算支付成功未发货和已发货这两种状态
	where2 := where
	if order.Status != 0 {
		where = where + fmt.Sprintf(" AND o.status = %v", order.Status)
		where2 = where
	} else {
		where2 = where2 + fmt.Sprintf(" AND o.status IN(%v,%v)", OrderPaySuccess, OrderDelivered)
	}
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			o.*,u.nickname
		FROM
			%v AS o
		INNER JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
		ORDER BY
			o.id DESC
		LIMIT ?,?
	`, TableH5Order, TableH5User, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&wr)
	if CheckError(err) {
		return nil, 0, 0, err
	}

	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS o INNER JOIN %v AS u ON o.uid = u.uid WHERE %v`,
		TableH5Order, TableH5User, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, 0, err
	}

	//计算支付金额
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(o.amount) is NULL,0,SUM(o.amount))
		FROM
			%v AS o
		INNER JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
	`, TableH5Order, TableH5User, where2)
	var amount int64
	o.Raw(sql).QueryRow(&amount)

	return wr, amount, count, nil
}

//合伙人代理的订单列表
func ListPartnerOrder(p ListParams, t ListDayParams, order AllOrderParams, multiOrm ...orm.Ormer) ([]orm.Params, int64, int64, error) {
	where := " 1 = 1"
	if order.Uid != 0 {
		where = where + fmt.Sprintf(" AND o.uid = %v", order.Uid)
	}
	if order.TransactionId != "" {
		where = where + fmt.Sprintf(" AND o.transaction_id = %v", order.TransactionId)
	}
	if order.Id != 0 {
		where = where + fmt.Sprintf(" AND o.id = %v", order.Id)
	}

	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND o.order_time >= %v AND o.order_time < %v", t.StartTime, t.EndTime)
	}
	//计算订单总金额时，默认只计算支付成功未发货和已发货这两种状态
	where2 := where
	if order.Status != 0 {
		where = where + fmt.Sprintf(" AND o.status = %v", order.Status)
		where2 = where
	} else {
		where2 = where2 + fmt.Sprintf(" AND o.status IN(%v,%v)", OrderPaySuccess, OrderDelivered)
	}
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			o.*,u.nickname
		FROM
			%v AS o
		LEFT JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
		ORDER BY
			o.id DESC
		LIMIT ?,?
	`, TablePfOrder, TablePfUser, where)
	o := NewOrm(multiOrm, DBChessPartner)
	var wr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&wr)
	if CheckError(err) {
		return wr, 0, 0, err
	}

	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS o LEFT JOIN %v AS u ON o.uid = u.uid WHERE %v`,
		TablePfOrder, TablePfUser, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return wr, 0, 0, err
	}

	//计算支付金额
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(o.amount) is NULL,0,SUM(o.amount))
		FROM
			%v AS o
		INNER JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
	`, TablePfOrder, TablePfUser, where2)
	var amount int64
	o.Raw(sql).QueryRow(&amount)
	return wr, amount, count, nil
}

//商城的订单列表
func ListAppOrder(p ListParams, t ListDayParams, order AllOrderParams, multiOrm ...orm.Ormer) ([]orm.Params, int64, int64, error) {
	where := " 1=1 "
	if order.Uid != 0 {
		where = where + fmt.Sprintf(" AND o.uid = %v", order.Uid)
	}
	if order.TransactionId != "" {
		where = where + fmt.Sprintf(" AND o.transaction_id = %v", order.TransactionId)
	}
	if order.Id != 0 {
		where = where + fmt.Sprintf(" AND o.id = %v", order.Id)
	}
	if order.PayType != 0 {
		where = where + fmt.Sprintf(" AND o.pay_type = %v", order.PayType)
	}
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND o.order_time >= %v AND o.order_time < %v", t.StartTime, t.EndTime)
	}

	//计算订单总金额时，默认只计算支付成功未发货和已发货这两种状态
	where2 := where
	if order.Status != 0 {
		where = where + fmt.Sprintf(" AND o.status = %v", order.Status)
		where2 = where
	} else {
		where2 = where2 + fmt.Sprintf(" AND o.status IN(%v,%v)", OrderPaySuccess, OrderDelivered)
	}
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			o.*,u.nickname
		FROM
			%v AS o
		LEFT JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
		ORDER BY
			o.id DESC
		LIMIT ?,?
	`, TableAppOrder, TableClientUser, where)
	o := NewOrm(multiOrm, DBChess)
	var wr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&wr)
	if CheckError(err) {
		return nil, 0, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v AS o
		LEFT JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE %v`,
		TableAppOrder, TableClientUser, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, 0, err
	}
	//计算支付金额
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(o.amount) is NULL,0,SUM(o.amount))
		FROM
			%v AS o
		INNER JOIN
			%v AS u
		ON o.uid = u.uid
		WHERE
			%v
	`, TableAppOrder, TableClientUser, where2)
	var amount int64
	o.Raw(sql).QueryRow(&amount)

	return wr, amount, count, nil
}

//某个具体的玩家的订单列表(H5店铺里的支付记录)
func ListPlayerH5Order(p ListParams, t ListDayParams, order AllOrderParams, multiOrm ...orm.Ormer) ([]*Order, int64, error) {
	where := "user_type = 2"
	if order.Uid != 0 {
		where = where + fmt.Sprintf(" AND uid = %v", order.Uid)
	}
	if order.TransactionId != "" {
		where = where + fmt.Sprintf(" AND transaction_id = %v", order.TransactionId)
	}
	if order.Id != 0 {
		where = where + fmt.Sprintf(" AND id = %v", order.Id)
	}
	if order.Status != 0 {
		where = where + fmt.Sprintf(" AND status = %v", order.Status)
	}

	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND order_time >= %v AND order_time < %v", t.StartTime, t.EndTime)
	}
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY
			id DESC
		LIMIT ?,?
	`, TableH5Order, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr []*Order
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&wr)
	if CheckError(err) {
		return nil, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`,
		TableH5Order, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return wr, count, nil
}

//某个具体的代理店铺里的支付记录
func ListAgentShopOrder(p ListParams, t ListDayParams, order AllOrderParams, multiOrm ...orm.Ormer) ([]*Order, int64, error) {
	where := fmt.Sprintf("agent_id = %v", order.AgentId)
	if order.Uid != 0 {
		where = where + fmt.Sprintf(" AND uid = %v", order.Uid)
	}
	if order.TransactionId != "" {
		where = where + fmt.Sprintf(" AND transaction_id = %v", order.TransactionId)
	}
	if order.Id != 0 {
		where = where + fmt.Sprintf(" AND id = %v", order.Id)
	}
	if order.Status != 0 {
		where = where + fmt.Sprintf(" AND status = %v", order.Status)
	}

	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND order_time >= %v AND order_time < %v", t.StartTime, t.EndTime)
	}
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY
			id DESC
		LIMIT ?,?
	`, TableH5Order, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr []*Order
	_, err := o.Raw(sql, limit, p.PageSize).QueryRows(&wr)
	if CheckError(err) {
		return nil, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v WHERE %v`,
		TableH5Order, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, err
	}
	return wr, count, nil
}

//具体某个代理的订单列表
func ListSingleAgentOrder(p ListParams, t ListDayParams, uid int64,
	multiOrm ...orm.Ormer) ([]orm.Params, int64, int64, error) {
	where := fmt.Sprintf("user_type = 1 AND status IN (%v,%v) AND uid = %v", OrderDelivered, OrderPaySuccess, uid)
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND order_time >= %v AND order_time < %v", t.StartTime, t.EndTime)
	}
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		ORDER BY
			id DESC
		LIMIT ?,?
	`, TableH5Order, where)
	o := NewOrm(multiOrm, DBChessCenter)
	var wr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&wr)
	if CheckError(err) {
		return nil, 0, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v  WHERE %v`,
		TableH5Order, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return nil, 0, 0, err
	}
	//统计支付金额
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(amount) is NULL,0,SUM(amount))
		FROM
			%v
		WHERE
			%v
	`, TableH5Order, where)
	var amount int64
	err = o.Raw(sql).QueryRow(&amount)
	if CheckError(err) {
		return nil, 0, 0, err
	}
	return wr, count, amount, nil
}

//统计代理的充值总金额
func StatAgentOrder(agentId interface{}, multiOrm ...orm.Ormer) int64 {
	where := fmt.Sprintf("user_type = 1 AND status IN (%v,%v) AND uid = %v",
		OrderDelivered, OrderPaySuccess, agentId)
	sql := fmt.Sprintf(`
		SELECT
			IF(SUM(amount) is NULL,0,SUM(amount))
		FROM
			%v
		WHERE
			%v
	`, TableH5Order, where)
	var amount int64
	o := NewOrm(multiOrm, DBChessCenter)
	o.Raw(sql).QueryRow(&amount)
	return amount
}
